﻿using Kingdee.BOS;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RK.SerivesPlugin.Ronma
{
    [Description("操作前-润马生产碎料反写。保存时校验工单号，审核时反写。"), HotUpdate]
    public class DzMiscSave : AbstractOperationServicePlugIn
    {
        public override void BeforeExecuteOperationTransaction(BeforeExecuteOperationTransaction e)
        {
            base.BeforeExecuteOperationTransaction(e);
            var operationNumber = this.FormOperation.Operation;
            var obj = e.SelectedRows.Select(x => x.DataEntity).FirstOrDefault();
            var billType = obj["BillTypeID"] as DynamicObject;
            var billTypeNumber = billType == null ? "" : billType["Number"].ToString();
            if (billTypeNumber == "SCFL")
            {
                var eRows = obj["STK_MISCELLANEOUSENTRY"] as DynamicObjectCollection;
                if (operationNumber == "Save")
                {
                    foreach (var eRow in eRows)
                    {
                        //工单检验
                        var moBillNo = eRow["F_PXIA_Text_qtr"] == null ? "" : eRow["F_PXIA_Text_qtr"].ToString();
                        var seq = Convert.ToInt32(eRow["Seq"]);
                        bool isMo = GetMoBillNo(moBillNo);
                        if (!isMo)
                        {
                            //e.Cancel = true;
                            throw new KDBusinessException("DzMiscSave-002", $"第{seq}行工单号：{moBillNo}，不存在，不允许保存！");
                        }
                        //备注校验
                        var entryNote = eRow["EntryNote"] == null ? "" : eRow["EntryNote"].ToString();
                        decimal noteQty = 0;
                        if (!decimal.TryParse(entryNote, out noteQty))
                        {
                            throw new KDBusinessException("DzMiscSave-003", $"第{seq}行备注：{entryNote}，不是有效的数字，不允许保存！");
                        }
                    }
                }
                if (operationNumber == "Audit")
                {
                    //反写数量到生产订单
                    foreach (var eRow in eRows)
                    {
                        var moBillNo = eRow["F_PXIA_Text_qtr"].ToString();
                        var seq = Convert.ToInt32(eRow["Seq"]);
                        var entryNote = eRow["EntryNote"] == null ? "" : eRow["EntryNote"].ToString();
                        decimal noteQty = 0;
                        if (!decimal.TryParse(entryNote, out noteQty))
                        {
                            throw new KDBusinessException("DzMiscSave-003", $"第{seq}行备注：{entryNote}，不是有效的数字，不允许审核！");
                        }
                        List<List<object>> moInfos = GetMoInfos(moBillNo);
                        decimal debQty = 0;
                        int moEId = 0;
                        if (moInfos.Count > 0)
                        {
                            debQty = Convert.ToDecimal(moInfos[0][1]);
                            moEId = Convert.ToInt32(moInfos[0][0]);
                        }
                        debQty += noteQty;
                        if (moEId > 0)
                        {
                            string sql = string.Format($"/*dialect*/ UPDATE T0 SET T0.F_DebrisInQty={debQty} FROM T_PRD_MOENTRY T0 WHERE T0.FENTRYID={moEId}");
                            DBServiceHelper.Execute(this.Context, sql);
                        }
                    }
                }
            }
        }

        private List<List<object>> GetMoInfos(string moBillNo)
        {
            var list = Api.ExecuteBillQuery(this.Context, "PRD_MO", "FTreeEntity_FEntryId,F_DebrisInQty", $"FBillNo='{moBillNo}' AND FDocumentStatus='C'", "FSeq", 2000);
            return list;
        }

        private bool GetMoBillNo(string moBillNo)
        {
            var list = Api.ExecuteBillQuery(this.Context, "PRD_MO", "FBillNo", $"FBillNo='{moBillNo}' AND FDocumentStatus='C'", "FBillNo", 2000);
            if (list.Count > 0 && Convert.ToString(list.FirstOrDefault().FirstOrDefault()) == moBillNo)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 加载所有列
        /// </summary>
        /// <param name="e"></param>
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            FormMetadata meta = MetaDataServiceHelper.GetFormMetaData(this.Context, this.BusinessInfo.GetForm().Id);
            var fieldKeyList = meta.BusinessInfo.GetBosFields().Select(x => x.Field.Key).ToList();
            for (int i = 0; i < fieldKeyList.Count; i++)
            {
                e.FieldKeys.Add(fieldKeyList[i]);
            }
        }
    }
}
